# -*- coding: utf-8 -*-
"""
综合演示插件 - 展示如何使用TG组件层和样式管理器
合并了组件演示、对话框演示和样式示例的功能
"""
import sys
import os

# 添加父目录到路径以便导入插件基类和组件
ui_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ui_dir not in sys.path:
    sys.path.insert(0, ui_dir)

# 导入插件基类
from plugin_base import PluginBase

# 导入组件 - 使用绝对导入
from ui.components import (
    TgLabel, TgButton, TgOutlineButton, TgTextEdit,
    TgLineEdit, TgComboBox, TgCheckBox, TgGroupBox,
    TgLayout, TgHBoxLayout, TgCard, TgButtonGroup, TgFormRow, TgToolBar, TgTable,
    TgBaseWidget, TgTabWidget, TgScrollArea
)
from ui.components.charts.html_table import TgHtmlTable
from ui.components.charts.bar_chart import TgBarChart
from ui.components.charts.surface_3d_chart import TgSurface3DChart

# 导入PySide6的消息框（这个还没有封装的组件）
from PySide6.QtWidgets import QMessageBox
from PySide6.QtCore import Qt


class PluginDemo(PluginBase):
    """综合演示插件"""
    
    def __init__(self):
        super().__init__()
        self._name = "TG Plugin Demo"
        self._version = "1.0.0"
        self._description = "TG组件层和样式管理器的综合演示"
        self._author = "TG Trader"
        self._widget = None
    
    def get_name(self) -> str:
        """获取插件名称"""
        return self._name
    
    def get_widget(self) -> TgScrollArea:
        """获取插件的主界面部件"""
        if self._widget is None:
            self._widget = self._create_widget()
        return self._widget
    
    def _create_widget(self) -> TgScrollArea:
        """创建插件界面"""
        # 创建滚动区域作为主容器
        scroll_area = TgScrollArea()
        
        # 创建主要内容部件
        main_widget = TgBaseWidget()
        main_layout = TgLayout(margins='medium', spacing='medium')
        
        # 创建选项卡
        tab_widget = TgTabWidget()
        
        # 基础组件选项卡
        basic_tab = self._create_basic_components_tab()
        tab_widget.addTab(basic_tab, "基础组件")
        
        # 复杂组件选项卡
        complex_tab = self._create_complex_components_tab()
        tab_widget.addTab(complex_tab, "复杂组件")
        
        # 表单组件选项卡
        form_tab = self._create_form_components_tab()
        tab_widget.addTab(form_tab, "表单组件")
        
        # 样式演示选项卡
        style_tab = self._create_style_demo_tab()
        tab_widget.addTab(style_tab, "样式演示")
        
        # 对话框演示选项卡
        dialog_tab = self._create_dialog_demo_tab()
        tab_widget.addTab(dialog_tab, "对话框演示")
        
        # 表格演示选项卡
        table_tab = self._create_table_demo_tab()
        tab_widget.addTab(table_tab, "表格演示")
        
        # HTML表格演示选项卡
        html_table_tab = self._create_html_table_demo_tab()
        tab_widget.addTab(html_table_tab, "HTML表格演示")
        
        # 柱状图演示选项卡
        bar_chart_tab = self._create_bar_chart_demo_tab()
        tab_widget.addTab(bar_chart_tab, "柱状图演示")
        
        # 3D曲面图演示选项卡
        surface_3d_tab = self._create_surface_3d_demo_tab()
        tab_widget.addTab(surface_3d_tab, "3D曲面图演示")
        
        main_layout.addWidget(tab_widget)
        main_widget.setLayout(main_layout)
        
        # 设置滚动区域
        scroll_area.setWidget(main_widget)
        
        return scroll_area
    
    def _create_basic_components_tab(self) -> TgScrollArea:
        """创建基础组件选项卡"""
        # 创建滚动区域
        scroll_area = TgScrollArea()
        
        tab = TgBaseWidget()
        layout = TgLayout(margins='medium', spacing='medium')
        
        # 标题
        title = TgLabel("基础组件演示", 'title', 'primary')
        layout.addWidget(title)
        
        # 标签演示
        label_group = TgGroupBox("标签组件")
        label_layout = TgLayout(margins='medium', spacing='small')
        
        normal_label = TgLabel("这是普通标签")
        desc_label = TgLabel("这是描述标签", 'description')
        title_label = TgLabel("这是标题标签", 'title', 'secondary')
        
        label_layout.addWidget(normal_label)
        label_layout.addWidget(desc_label)
        label_layout.addWidget(title_label)
        label_group.setLayout(label_layout)
        layout.addWidget(label_group)
        
        # 按钮演示
        button_group = TgGroupBox("按钮组件")
        button_layout = TgLayout(margins='medium', spacing='medium')
        
        # 主题按钮组
        theme_label = TgLabel("不同主题的按钮：", 'normal')
        button_layout.addWidget(theme_label)
        
        button_row1 = TgBaseWidget()
        button_row1_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        primary_btn = TgButton("主要按钮", 'primary', 'medium')
        secondary_btn = TgButton("次要按钮", 'secondary', 'medium')
        danger_btn = TgButton("危险按钮", 'danger', 'medium')
        
        button_row1_layout.addWidget(primary_btn)
        button_row1_layout.addWidget(secondary_btn)
        button_row1_layout.addWidget(danger_btn)
        button_row1_layout.addStretch()
        button_row1.setLayout(button_row1_layout)
        button_layout.addWidget(button_row1)
        
        # 尺寸按钮组
        size_label = TgLabel("不同尺寸的按钮：", 'normal')
        button_layout.addWidget(size_label)
        
        button_row2 = TgBaseWidget()
        button_row2_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        large_btn = TgButton("大按钮", 'primary', 'large')
        medium_btn = TgButton("中按钮", 'primary', 'medium')
        small_btn = TgButton("小按钮", 'primary', 'small')
        
        button_row2_layout.addWidget(large_btn)
        button_row2_layout.addWidget(medium_btn)
        button_row2_layout.addWidget(small_btn)
        button_row2_layout.addStretch()
        button_row2.setLayout(button_row2_layout)
        button_layout.addWidget(button_row2)
        
        # 轮廓按钮组
        outline_label = TgLabel("轮廓按钮：", 'normal')
        button_layout.addWidget(outline_label)
        
        outline_row = TgBaseWidget()
        outline_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        outline_btn1 = TgOutlineButton("轮廓按钮", 'primary')
        outline_btn2 = TgOutlineButton("删除按钮", 'danger')
        
        outline_layout.addWidget(outline_btn1)
        outline_layout.addWidget(outline_btn2)
        outline_layout.addStretch()
        outline_row.setLayout(outline_layout)
        button_layout.addWidget(outline_row)
        
        button_group.setLayout(button_layout)
        layout.addWidget(button_group)
        
        # 输入组件演示
        input_group = TgGroupBox("输入组件")
        input_layout = TgLayout(margins='medium', spacing='medium')
        
        input_label = TgLabel("输入控件示例：", 'normal')
        input_layout.addWidget(input_label)
        
        input_container = TgBaseWidget()
        input_container_layout = TgLayout(margins='none', spacing='small')
        
        line_edit = TgLineEdit("请输入文本...")
        combo_box = TgComboBox()
        combo_box.addItems(["选项1", "选项2", "选项3"])
        checkbox = TgCheckBox("复选框选项")
        
        input_container_layout.addWidget(line_edit)
        input_container_layout.addWidget(combo_box)
        input_container_layout.addWidget(checkbox)
        input_container.setLayout(input_container_layout)
        input_layout.addWidget(input_container)
        
        input_group.setLayout(input_layout)
        layout.addWidget(input_group)
        
        # 文本编辑器
        text_group = TgGroupBox("文本编辑器")
        text_layout = TgLayout(margins='medium', spacing='small')
        
        text_edit = TgTextEdit("这是一个样式化的文本编辑器...\n\n您可以在这里输入多行文本。")
        text_edit.setMaximumHeight(120)
        text_layout.addWidget(text_edit)
        
        text_group.setLayout(text_layout)
        layout.addWidget(text_group)
        
        layout.addStretch()
        tab.setLayout(layout)
        
        scroll_area.setWidget(tab)
        return scroll_area
    
    def _create_complex_components_tab(self) -> TgScrollArea:
        """创建复杂组件选项卡"""
        scroll_area = TgScrollArea()
        
        tab = TgBaseWidget()
        layout = TgLayout(margins='medium', spacing='medium')
        
        # 标题
        title = TgLabel("复杂组件演示", 'title', 'primary')
        layout.addWidget(title)
        
        # 卡片组件演示
        card_group = TgGroupBox("卡片组件")
        card_layout = TgLayout(margins='medium', spacing='medium')
        
        card_row1 = TgBaseWidget()
        card_row1_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        card1 = TgCard("功能卡片", "这是一个功能卡片的示例，展示了如何组合基础组件创建复杂组件。")
        card2 = TgCard("信息卡片", "卡片组件支持鼠标悬停效果，并且可以包含任意内容。")
        
        card_row1_layout.addWidget(card1)
        card_row1_layout.addWidget(card2)
        card_row1.setLayout(card_row1_layout)
        card_layout.addWidget(card_row1)
        
        card_row2 = TgBaseWidget()
        card_row2_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        card3 = TgCard("", "这是一个没有标题的卡片示例。")
        card4 = TgCard("交互卡片", "卡片可以包含各种交互元素。")
        
        card_row2_layout.addWidget(card3)
        card_row2_layout.addWidget(card4)
        card_row2.setLayout(card_row2_layout)
        card_layout.addWidget(card_row2)
        
        card_group.setLayout(card_layout)
        layout.addWidget(card_group)
        
        # 按钮组演示
        button_group_demo = TgGroupBox("按钮组组件")
        button_group_layout = TgLayout(margins='medium', spacing='medium')
        
        desc_label = TgLabel("点击按钮组中的按钮查看效果：", 'description')
        button_group_layout.addWidget(desc_label)
        
        button_group_container = TgBaseWidget()
        button_group_container_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        self.button_group1 = TgButtonGroup([
            "保存",
            {"text": "取消", "theme": "danger"},
            {"text": "重置", "theme": "secondary", "size": "medium"}
        ])
        self.button_group1.button_clicked.connect(self._on_button_group_clicked)
        
        button_group_container_layout.addWidget(self.button_group1)
        button_group_container_layout.addStretch()
        button_group_container.setLayout(button_group_container_layout)
        button_group_layout.addWidget(button_group_container)
        
        self.result_label = TgLabel("等待按钮点击...", 'normal')
        button_group_layout.addWidget(self.result_label)
        
        button_group_demo.setLayout(button_group_layout)
        layout.addWidget(button_group_demo)
        
        # 工具栏演示
        toolbar_group = TgGroupBox("工具栏组件")
        toolbar_layout = TgLayout(margins='medium', spacing='medium')
        
        toolbar_desc = TgLabel("工具栏示例：", 'description')
        toolbar_layout.addWidget(toolbar_desc)
        
        toolbar = TgToolBar()
        new_btn = toolbar.add_button("新建", 'primary', 'small')
        open_btn = toolbar.add_button("打开", 'secondary', 'small')
        toolbar.add_separator()
        save_btn = toolbar.add_button("保存", 'primary', 'small')
        toolbar.add_separator()
        toolbar.add_spacer()
        help_btn = toolbar.add_button("帮助", 'primary', 'small')
        
        new_btn.clicked.connect(lambda: self._show_toolbar_action("新建"))
        open_btn.clicked.connect(lambda: self._show_toolbar_action("打开"))
        save_btn.clicked.connect(lambda: self._show_toolbar_action("保存"))
        help_btn.clicked.connect(lambda: self._show_toolbar_action("帮助"))
        
        toolbar_layout.addWidget(toolbar)
        
        self.toolbar_result = TgLabel("等待工具栏操作...", 'normal')
        toolbar_layout.addWidget(self.toolbar_result)
        
        toolbar_group.setLayout(toolbar_layout)
        layout.addWidget(toolbar_group)
        
        layout.addStretch()
        tab.setLayout(layout)
        
        scroll_area.setWidget(tab)
        return scroll_area
    
    def _create_form_components_tab(self) -> TgScrollArea:
        """创建表单组件选项卡"""
        scroll_area = TgScrollArea()
        
        tab = TgBaseWidget()
        layout = TgLayout(margins='medium', spacing='medium')
        
        # 标题
        title = TgLabel("表单组件演示", 'title', 'primary')
        layout.addWidget(title)
        
        # 表单组
        form_group = TgGroupBox("用户信息表单")
        form_layout = TgLayout(margins='medium', spacing='medium')
        
        form_desc = TgLabel("请填写以下信息：", 'description')
        form_layout.addWidget(form_desc)
        
        form_container = TgBaseWidget()
        form_container_layout = TgLayout(margins='none', spacing='small')
        
        self.name_row = TgFormRow("姓名:", TgLineEdit("请输入姓名"))
        self.email_row = TgFormRow("邮箱:", TgLineEdit("请输入邮箱地址"))
        
        gender_combo = TgComboBox()
        gender_combo.addItems(["男", "女", "其他"])
        self.gender_row = TgFormRow("性别:", gender_combo)
        
        self.subscribe_row = TgFormRow("订阅通知:", TgCheckBox("接收邮件通知"))
        
        bio_text = TgTextEdit("请输入个人简介...")
        bio_text.setMaximumHeight(80)
        self.bio_row = TgFormRow("个人简介:", bio_text)
        
        form_container_layout.addWidget(self.name_row)
        form_container_layout.addWidget(self.email_row)
        form_container_layout.addWidget(self.gender_row)
        form_container_layout.addWidget(self.subscribe_row)
        form_container_layout.addWidget(self.bio_row)
        
        form_container.setLayout(form_container_layout)
        form_layout.addWidget(form_container)
        
        button_container = TgBaseWidget()
        button_container_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        form_buttons = TgButtonGroup([
            {"text": "提交", "theme": "primary"},
            {"text": "重置", "theme": "secondary"},
            {"text": "取消", "theme": "danger"}
        ])
        form_buttons.button_clicked.connect(self._on_form_button_clicked)
        
        button_container_layout.addWidget(form_buttons)
        button_container_layout.addStretch()
        button_container.setLayout(button_container_layout)
        form_layout.addWidget(button_container)
        
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 结果显示
        result_group = TgGroupBox("操作结果")
        result_layout = TgLayout(margins='medium', spacing='small')
        
        self.form_result = TgTextEdit("表单操作结果将显示在这里...")
        self.form_result.setMaximumHeight(150)
        result_layout.addWidget(self.form_result)
        
        result_group.setLayout(result_layout)
        layout.addWidget(result_group)
        
        layout.addStretch()
        tab.setLayout(layout)
        
        scroll_area.setWidget(tab)
        return scroll_area
    
    def _create_style_demo_tab(self) -> TgScrollArea:
        """创建样式演示选项卡"""
        scroll_area = TgScrollArea()
        
        tab = TgBaseWidget()
        layout = TgLayout(margins='medium', spacing='medium')
        
        # 标题
        title = TgLabel("样式管理器演示", 'title', 'primary')
        layout.addWidget(title)
        
        desc_label = TgLabel("展示统一样式管理器的使用方法", 'description')
        layout.addWidget(desc_label)
        
        # 按钮样式示例
        button_group = TgGroupBox("按钮样式示例")
        button_layout = TgLayout(margins='medium', spacing='small')
        
        # 不同尺寸的按钮
        size_container = TgBaseWidget()
        size_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        small_btn = TgButton("小按钮", 'primary', 'small')
        medium_btn = TgButton("中按钮", 'primary', 'medium')
        large_btn = TgButton("大按钮", 'primary', 'large')
        
        size_layout.addWidget(small_btn)
        size_layout.addWidget(medium_btn)
        size_layout.addWidget(large_btn)
        size_layout.addStretch()
        size_container.setLayout(size_layout)
        button_layout.addWidget(size_container)
        
        # 轮廓按钮
        outline_container = TgBaseWidget()
        outline_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        outline_btn1 = TgOutlineButton("危险操作", 'danger')
        outline_btn2 = TgOutlineButton("主要操作", 'primary')
        
        outline_layout.addWidget(outline_btn1)
        outline_layout.addWidget(outline_btn2)
        outline_layout.addStretch()
        outline_container.setLayout(outline_layout)
        button_layout.addWidget(outline_container)
        
        button_group.setLayout(button_layout)
        layout.addWidget(button_group)
        
        # 主题色彩示例
        theme_group = TgGroupBox("主题色彩示例")
        theme_layout = TgLayout(margins='medium', spacing='small')
        
        # Primary主题
        primary_title = TgLabel("Primary 主题", 'title', 'primary')
        theme_layout.addWidget(primary_title)
        
        primary_btn = TgButton("Primary 按钮", 'primary')
        theme_layout.addWidget(primary_btn)
        
        # Secondary主题
        secondary_title = TgLabel("Secondary 主题", 'title', 'secondary')
        theme_layout.addWidget(secondary_title)
        
        secondary_btn = TgButton("Secondary 按钮", 'secondary')
        theme_layout.addWidget(secondary_btn)
        
        # Danger主题
        danger_btn = TgButton("Danger 按钮", 'danger')
        theme_layout.addWidget(danger_btn)
        
        theme_group.setLayout(theme_layout)
        layout.addWidget(theme_group)
        
        # 文本区域示例
        text_group = TgGroupBox("文本区域示例")
        text_layout = TgLayout(margins='medium', spacing='small')
        
        text_area = TgTextEdit("""这是一个使用TG组件的文本区域示例。

TG组件的优势：
1. 统一的UI风格
2. 易于维护和更新
3. 减少重复代码
4. 支持主题切换

使用方法：
- 导入插件基类：from plugin_base import PluginBase
- 继承插件基类：class MyPlugin(PluginBase)
- 使用TG组件：from ui.components import TgButton, TgLabel...

支持的组件类型：
- 基础组件：TgLabel, TgButton, TgLineEdit...
- 容器组件：TgGroupBox, TgLayout, TgScrollArea...
- 复合组件：TgCard, TgButtonGroup, TgFormRow...""")
        
        text_layout.addWidget(text_area)
        
        text_group.setLayout(text_layout)
        layout.addWidget(text_group)
        
        layout.addStretch()
        tab.setLayout(layout)
        
        scroll_area.setWidget(tab)
        return scroll_area
    
    def _create_table_demo_tab(self) -> TgScrollArea:
        """创建表格演示选项卡"""
        scroll_area = TgScrollArea()
        
        tab = TgBaseWidget()
        layout = TgLayout(margins='medium', spacing='medium')
        
        # 标题
        title = TgLabel("表格演示", 'title', 'primary')
        layout.addWidget(title)
        
        desc_label = TgLabel("展示表格组件的各种功能", 'description')
        layout.addWidget(desc_label)
        
        # 基础表格示例
        basic_table_group = TgGroupBox("基础表格")
        basic_table_layout = TgLayout(margins='medium', spacing='medium')
        
        # 创建示例数据
        headers = ["姓名", "年龄", "城市", "职业"]
        data = [
            ["张三", "25", "北京", "工程师"],
            ["李四", "30", "上海", "设计师"],
            ["王五", "28", "广州", "产品经理"],
            ["赵六", "35", "深圳", "数据分析师"],
            ["孙七", "26", "杭州", "前端开发"],
            ["周八", "32", "成都", "后端开发"],
            ["吴九", "29", "武汉", "测试工程师"],
            ["郑十", "33", "西安", "运维工程师"]
        ]
        
        # 创建表格
        self.demo_table = TgTable(headers, data)
        self.demo_table.setMaximumHeight(300)
        
        # 连接表格信号
        self.demo_table.cell_clicked.connect(self._on_table_cell_clicked)
        self.demo_table.cell_double_clicked.connect(self._on_table_cell_double_clicked)
        self.demo_table.selection_changed.connect(self._on_table_selection_changed)
        
        basic_table_layout.addWidget(self.demo_table)
        basic_table_group.setLayout(basic_table_layout)
        layout.addWidget(basic_table_group)
        
        # 表格操作按钮
        operation_group = TgGroupBox("表格操作")
        operation_layout = TgLayout(margins='medium', spacing='medium')
        
        # 操作按钮行
        button_row = TgBaseWidget()
        button_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        add_btn = TgButton("添加行", 'primary', 'medium')
        add_btn.clicked.connect(self._add_table_row)
        
        remove_btn = TgButton("删除选中行", 'danger', 'medium')
        remove_btn.clicked.connect(self._remove_table_row)
        
        clear_btn = TgButton("清空表格", 'secondary', 'medium')
        clear_btn.clicked.connect(self._clear_table)
        
        resize_btn = TgButton("自适应列宽", 'secondary', 'medium')
        resize_btn.clicked.connect(self._resize_table_columns)
        
        auto_height_btn = TgButton("自适应高度", 'secondary', 'medium')
        auto_height_btn.clicked.connect(self._toggle_auto_height)
        
        button_layout.addWidget(add_btn)
        button_layout.addWidget(remove_btn)
        button_layout.addWidget(clear_btn)
        button_layout.addWidget(resize_btn)
        button_layout.addWidget(auto_height_btn)
        button_layout.addStretch()
        button_row.setLayout(button_layout)
        
        operation_layout.addWidget(button_row)
        operation_group.setLayout(operation_layout)
        layout.addWidget(operation_group)
        
        # 表格事件显示
        event_group = TgGroupBox("表格事件")
        event_layout = TgLayout(margins='medium', spacing='small')
        
        self.table_event_display = TgTextEdit("表格事件信息将显示在这里...")
        self.table_event_display.setMaximumHeight(100)
        event_layout.addWidget(self.table_event_display)
        
        event_group.setLayout(event_layout)
        layout.addWidget(event_group)
        
        layout.addStretch()
        tab.setLayout(layout)
        
        scroll_area.setWidget(tab)
        return scroll_area
    
    def _create_dialog_demo_tab(self) -> TgScrollArea:
        """创建对话框演示选项卡"""
        scroll_area = TgScrollArea()
        
        tab = TgBaseWidget()
        layout = TgLayout(margins='medium', spacing='medium')
        
        # 标题
        title = TgLabel("对话框演示", 'title', 'primary')
        layout.addWidget(title)
        
        desc_label = TgLabel("点击下面的按钮，将弹出不同类型的对话框", 'description')
        layout.addWidget(desc_label)
        
        # 对话框示例组
        dialog_group = TgGroupBox("对话框示例")
        dialog_layout = TgLayout(margins='medium', spacing='medium')
        
        # Hello World对话框
        hello_container = TgBaseWidget()
        hello_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        hello_btn = TgButton("Hello World 对话框", 'secondary', 'large')
        hello_btn.clicked.connect(self._show_hello_dialog)
        
        hello_layout.addWidget(hello_btn)
        hello_layout.addStretch()
        hello_container.setLayout(hello_layout)
        dialog_layout.addWidget(hello_container)
        
        # 信息对话框
        info_container = TgBaseWidget()
        info_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        info_btn = TgButton("信息对话框", 'primary', 'medium')
        info_btn.clicked.connect(self._show_info_dialog)
        
        warning_btn = TgButton("警告对话框", 'danger', 'medium')
        warning_btn.clicked.connect(self._show_warning_dialog)
        
        info_layout.addWidget(info_btn)
        info_layout.addWidget(warning_btn)
        info_layout.addStretch()
        info_container.setLayout(info_layout)
        dialog_layout.addWidget(info_container)
        
        # 确认对话框
        confirm_container = TgBaseWidget()
        confirm_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        confirm_btn = TgButton("确认对话框", 'secondary', 'medium')
        confirm_btn.clicked.connect(self._show_confirm_dialog)
        
        confirm_layout.addWidget(confirm_btn)
        confirm_layout.addStretch()
        confirm_container.setLayout(confirm_layout)
        dialog_layout.addWidget(confirm_container)
        
        dialog_group.setLayout(dialog_layout)
        layout.addWidget(dialog_group)
        
        # 结果显示
        result_group = TgGroupBox("对话框结果")
        result_layout = TgLayout(margins='medium', spacing='small')
        
        self.dialog_result = TgTextEdit("对话框操作结果将显示在这里...")
        self.dialog_result.setMaximumHeight(100)
        result_layout.addWidget(self.dialog_result)
        
        result_group.setLayout(result_layout)
        layout.addWidget(result_group)
        
        layout.addStretch()
        tab.setLayout(layout)
        
        scroll_area.setWidget(tab)
        return scroll_area
    
    def _create_html_table_demo_tab(self) -> TgScrollArea:
        """创建HTML表格演示选项卡"""
        scroll_area = TgScrollArea()
        
        tab = TgBaseWidget()
        layout = TgLayout(margins='medium', spacing='medium')
        
        # 标题
        title = TgLabel("HTML表格演示", 'title', 'primary')
        layout.addWidget(title)
        
        desc_label = TgLabel("展示HTML表格组件的各种功能，包括图表、排序和样式", 'description')
        layout.addWidget(desc_label)
        
        # HTML表格组
        html_table_group = TgGroupBox("HTML表格功能")
        html_table_layout = TgLayout(margins='medium', spacing='medium')
        
        # 操作按钮行
        button_row = TgBaseWidget()
        button_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        load_sample_btn = TgButton("加载示例数据", 'primary', 'medium')
        load_sample_btn.clicked.connect(self._load_html_sample_data)
        
        profit_loss_btn = TgButton("设置盈亏样式", 'secondary', 'medium')
        profit_loss_btn.clicked.connect(self._set_html_profit_loss_style)
        
        chart_btn = TgButton("设置走势图", 'secondary', 'medium')
        chart_btn.clicked.connect(self._set_html_chart_column)
        
        toggle_sort_btn = TgButton("切换排序", 'secondary', 'medium')
        toggle_sort_btn.clicked.connect(self._toggle_html_sorting)
        
        add_row_btn = TgButton("添加行", 'primary', 'medium')
        add_row_btn.clicked.connect(self._add_html_sample_row)
        
        clear_btn = TgButton("清空数据", 'danger', 'medium')
        clear_btn.clicked.connect(self._clear_html_data)
        
        button_layout.addWidget(load_sample_btn)
        button_layout.addWidget(profit_loss_btn)
        button_layout.addWidget(chart_btn)
        button_layout.addWidget(toggle_sort_btn)
        button_layout.addWidget(add_row_btn)
        button_layout.addWidget(clear_btn)
        button_layout.addStretch()
        button_row.setLayout(button_layout)
        
        html_table_layout.addWidget(button_row)
        
        # 创建HTML表格
        self.html_table = TgHtmlTable()
        html_table_layout.addWidget(self.html_table)
        
        html_table_group.setLayout(html_table_layout)
        layout.addWidget(html_table_group)
        
        # 操作状态显示
        status_group = TgGroupBox("操作状态")
        status_layout = TgLayout(margins='medium', spacing='small')
        
        self.html_status_display = TgTextEdit("HTML表格操作状态将显示在这里...")
        self.html_status_display.setMaximumHeight(100)
        status_layout.addWidget(self.html_status_display)
        
        status_group.setLayout(status_layout)
        layout.addWidget(status_group)
        
        # 初始化加载示例数据
        self._load_html_sample_data()
        
        layout.addStretch()
        tab.setLayout(layout)
        
        scroll_area.setWidget(tab)
        return scroll_area
    
    def _load_html_sample_data(self):
        """加载HTML表格示例数据"""
        import random
        
        headers = ["股票代码", "股票名称", "最新价", "涨跌幅", "涨跌额", "近期走势", "成交量", "成交额"]
        
        # 生成包含走势数据的示例数据
        data = []
        stocks = [
            ("000001", "平安银行", 12.50, 2.35, 0.29),
            ("000002", "万科A", 25.80, -1.20, -0.31),
            ("000858", "五粮液", 158.90, 3.45, 5.30),
            ("000876", "新希望", 18.20, -2.15, -0.40),
            ("600519", "贵州茅台", 1950.00, 1.85, 35.40),
            ("600036", "招商银行", 42.60, -0.50, -0.21),
            ("000858", "腾讯控股", 385.20, 4.20, 15.50),
        ]
        
        for code, name, price, change_pct, change_amt in stocks:
            # 生成近期走势数据（10个交易日的价格）
            trend_data = self._generate_html_trend_data(price, change_pct, 10)
            trend_str = ",".join([f"{x:.2f}" for x in trend_data])
            
            volume = f"{random.randint(50, 500)}.{random.randint(0, 9)}万"
            amount = f"{random.randint(1, 50)}.{random.randint(0, 99)}亿"
            
            row = [code, name, f"{price:.2f}", f"{change_pct:+.2f}%", f"{change_amt:+.2f}", 
                   trend_str, volume, amount]
            data.append(row)
        
        self.html_table.update_data(headers, data)
        self.html_status_display.setPlainText("示例数据已加载")
    
    def _generate_html_trend_data(self, current_price, final_change_pct, days=10):
        """生成模拟的走势数据"""
        import random
        
        # 从当前价格往回推算历史价格
        prices = []
        price = current_price
        
        # 生成随机的日涨跌幅
        daily_changes = []
        remaining_change = final_change_pct
        
        for i in range(days - 1):
            # 随机生成一个涨跌幅，但要考虑总体趋势
            daily_change = random.uniform(-3, 3)
            if abs(remaining_change) > 1:
                # 如果还有较大的剩余变化，倾向于朝目标方向变化
                if remaining_change > 0:
                    daily_change = abs(daily_change) * random.choice([1, -0.3])
                else:
                    daily_change = -abs(daily_change) * random.choice([1, -0.3])
            
            daily_changes.append(daily_change)
            remaining_change -= daily_change
        
        # 最后一天的变化确保达到目标
        daily_changes.append(remaining_change)
        
        # 计算历史价格
        for i in range(days - 1, -1, -1):
            if i == days - 1:
                prices.append(current_price)
            else:
                prev_price = prices[0]
                # 计算前一天的价格
                historical_price = prev_price / (1 + daily_changes[i] / 100)
                prices.insert(0, historical_price)
        
        return prices
    
    def _set_html_profit_loss_style(self):
        """设置HTML表格盈亏样式"""
        # 对"涨跌幅"和"涨跌额"列应用盈亏样式
        self.html_table.set_profit_loss_style([3, 4], use_gradient=True, color_type='background')
        self.html_status_display.setPlainText("盈亏样式已设置到涨跌幅和涨跌额列")
    
    def _set_html_chart_column(self):
        """设置HTML表格图表列"""
        # 对"近期走势"列设置图表显示
        chart_config = {
            'width': 120,
            'height': 35,
            'positive_color': '#f44336',  # 红色上涨
            'negative_color': '#4caf50',  # 绿色下跌
            'show_percent': False
        }
        try:
            self.html_table.set_chart_column(5, chart_config)  # 使用索引5对应"近期走势"列
            self.html_status_display.setPlainText("走势图已设置到近期走势列")
        except Exception as e:
            self.html_status_display.setPlainText(f"设置图表列时出错: {e}")
    
    def _toggle_html_sorting(self):
        """切换HTML表格排序功能"""
        current_state = self.html_table._sorting_enabled
        self.html_table.enable_sorting(not current_state)
        status = "启用" if not current_state else "禁用"
        self.html_status_display.setPlainText(f"排序功能已{status}")
    
    def _add_html_sample_row(self):
        """添加HTML表格示例行"""
        import random
        
        codes = ["300750", "002415", "000725", "600588"]
        names = ["宁德时代", "海康威视", "京东方A", "用友网络"]
        
        code = random.choice(codes)
        name = random.choice(names)
        price = round(random.uniform(10, 200), 2)
        change_pct = round(random.uniform(-5, 5), 2)
        change_amt = round(price * change_pct / 100, 2)
        
        # 生成走势数据
        trend_data = self._generate_html_trend_data(price, change_pct, 10)
        trend_str = ",".join([f"{x:.2f}" for x in trend_data])
        
        volume = f"{random.randint(50, 500)}.{random.randint(0, 9)}万"
        amount = f"{random.randint(1, 50)}.{random.randint(0, 99)}亿"
        
        new_row = [code, name, f"{price:.2f}", f"{change_pct:+.2f}%", f"{change_amt:+.2f}", 
                   trend_str, volume, amount]
        self.html_table.add_row(new_row)
        self.html_status_display.setPlainText(f"添加新行: {code} {name}")
    
    def _clear_html_data(self):
        """清空HTML表格数据"""
        self.html_table.clear_data()
        self.html_status_display.setPlainText("HTML表格数据已清空")
    
    def _on_button_group_clicked(self, button_text):
        """按钮组点击事件处理"""
        self.result_label.setText(f"您点击了: {button_text}")
    
    def _show_toolbar_action(self, action):
        """工具栏操作显示"""
        self.toolbar_result.setText(f"执行了工具栏操作: {action}")
    
    def _on_form_button_clicked(self, button_text):
        """表单按钮点击事件处理"""
        if button_text == "提交":
            form_data = {
                "姓名": self.name_row.get_value(),
                "邮箱": self.email_row.get_value(),
                "性别": self.gender_row.get_value(),
                "订阅通知": self.subscribe_row.get_value(),
                "个人简介": self.bio_row.get_value()
            }
            
            result_text = "表单提交成功！\n\n收集到的数据:\n"
            for key, value in form_data.items():
                result_text += f"{key}: {value}\n"
            
            self.form_result.setPlainText(result_text)
            
        elif button_text == "重置":
            self.name_row.set_value("")
            self.email_row.set_value("")
            self.gender_row.set_value("男")
            self.subscribe_row.set_value(False)
            self.bio_row.set_value("")
            self.form_result.setPlainText("表单已重置")
            
        elif button_text == "取消":
            self.form_result.setPlainText("表单操作已取消")
    
    def _show_hello_dialog(self):
        """显示Hello World对话框"""
        msg_box = QMessageBox(self._widget)
        msg_box.setWindowTitle("Hello World")
        msg_box.setText("Hello World!")
        msg_box.setInformativeText("这是一个简单的Hello World对话框示例。")
        msg_box.setIcon(QMessageBox.Icon.Information)
        msg_box.setStandardButtons(QMessageBox.StandardButton.Ok)
        
        # 使用样式管理器设置对话框样式
        msg_box.setStyleSheet(self._style_manager.get_message_box_style('secondary'))
        
        result = msg_box.exec()
        self.dialog_result.setPlainText("Hello World对话框已显示")
    
    def _show_info_dialog(self):
        """显示信息对话框"""
        msg_box = QMessageBox(self._widget)
        msg_box.setWindowTitle("信息")
        msg_box.setText("这是一个信息对话框")
        msg_box.setInformativeText("用于显示重要信息给用户。")
        msg_box.setIcon(QMessageBox.Icon.Information)
        msg_box.setStandardButtons(QMessageBox.StandardButton.Ok)
        
        msg_box.setStyleSheet(self._style_manager.get_message_box_style('primary'))
        
        result = msg_box.exec()
        self.dialog_result.setPlainText("信息对话框已显示")
    
    def _show_warning_dialog(self):
        """显示警告对话框"""
        msg_box = QMessageBox(self._widget)
        msg_box.setWindowTitle("警告")
        msg_box.setText("这是一个警告对话框")
        msg_box.setInformativeText("用于提醒用户注意重要事项。")
        msg_box.setIcon(QMessageBox.Icon.Warning)
        msg_box.setStandardButtons(QMessageBox.StandardButton.Ok)
        
        msg_box.setStyleSheet(self._style_manager.get_message_box_style('danger'))
        
        result = msg_box.exec()
        self.dialog_result.setPlainText("警告对话框已显示")
    
    def _show_confirm_dialog(self):
        """显示确认对话框"""
        msg_box = QMessageBox(self._widget)
        msg_box.setWindowTitle("确认")
        msg_box.setText("是否确认执行此操作？")
        msg_box.setInformativeText("此操作不可撤销，请谨慎选择。")
        msg_box.setIcon(QMessageBox.Icon.Question)
        msg_box.setStandardButtons(
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        
        msg_box.setStyleSheet(self._style_manager.get_message_box_style('secondary'))
        
        result = msg_box.exec()
        if result == QMessageBox.StandardButton.Yes:
            self.dialog_result.setPlainText("确认对话框 - 用户选择：是")
        else:
            self.dialog_result.setPlainText("确认对话框 - 用户选择：否")
    
    def activate(self):
        """激活插件时调用"""
        print(f"Plugin {self.get_name()} activated")
    
    def initialize(self):
        """初始化插件"""
        print(f"Plugin {self.get_name()} initialized")
    
    def cleanup(self):
        """清理插件资源"""
        print(f"Plugin {self.get_name()} cleaned up")
    
    # 表格事件处理方法
    def _on_table_cell_clicked(self, row, column):
        """处理表格单元格点击事件"""
        cell_data = self.demo_table.get_cell_data(row, column)
        self.table_event_display.setPlainText(f"单击单元格 ({row}, {column}): {cell_data}")
    
    def _on_table_cell_double_clicked(self, row, column):
        """处理表格单元格双击事件"""
        cell_data = self.demo_table.get_cell_data(row, column)
        self.table_event_display.setPlainText(f"双击单元格 ({row}, {column}): {cell_data}")
    
    def _on_table_selection_changed(self):
        """处理表格选择变化事件"""
        selected_row = self.demo_table.get_selected_row()
        if selected_row is not None:
            selected_data = self.demo_table.get_selected_data()
            self.table_event_display.setPlainText(f"选择了第 {selected_row} 行: {selected_data}")
        else:
            self.table_event_display.setPlainText("没有选中行")
    
    def _add_table_row(self):
        """添加表格行"""
        import random
        names = ["新用户", "测试用户", "示例用户", "临时用户"]
        ages = ["22", "25", "28", "30", "35"]
        cities = ["北京", "上海", "广州", "深圳", "杭州"]
        jobs = ["开发者", "设计师", "产品经理", "测试工程师"]
        
        new_row = [
            random.choice(names),
            random.choice(ages),
            random.choice(cities),
            random.choice(jobs)
        ]
        
        self.demo_table.add_row(new_row)
        self.table_event_display.setPlainText(f"添加了新行: {new_row}")
    
    def _remove_table_row(self):
        """删除选中的表格行"""
        selected_row = self.demo_table.get_selected_row()
        if selected_row is not None:
            selected_data = self.demo_table.get_selected_data()
            self.demo_table.remove_row(selected_row)
            self.table_event_display.setPlainText(f"删除了第 {selected_row} 行: {selected_data}")
        else:
            self.table_event_display.setPlainText("请先选择要删除的行")
    
    def _clear_table(self):
        """清空表格"""
        self.demo_table.clear_data()
        self.table_event_display.setPlainText("表格已清空")
    
    def _resize_table_columns(self):
        """调整表格列宽"""
        self.demo_table.resize_columns_to_contents()
        self.table_event_display.setPlainText("已调整列宽以适应内容")
    
    def _toggle_auto_height(self):
        """切换表格自适应高度"""
        if hasattr(self.demo_table, '_auto_height') and self.demo_table._auto_height:
            # 当前是自适应高度，切换为固定高度
            self.demo_table.set_auto_height(False)
            self.demo_table.setMaximumHeight(300)  # 恢复最大高度限制
            self.table_event_display.setPlainText("已关闭自适应高度，恢复固定高度")
        else:
            # 当前是固定高度，切换为自适应高度
            self.demo_table.setMaximumHeight(16777215)  # 移除最大高度限制
            self.demo_table.set_auto_height(True, max_height=500)  # 设置最大高度为500px
            self.table_event_display.setPlainText("已启用自适应高度，最大高度500px")
    
    def _create_bar_chart_demo_tab(self) -> TgScrollArea:
        """创建柱状图演示选项卡"""
        scroll_area = TgScrollArea()
        
        tab = TgBaseWidget()
        layout = TgLayout(margins='medium', spacing='medium')
        
        # 标题
        title = TgLabel("柱状图演示", 'title', 'primary')
        layout.addWidget(title)
        
        desc_label = TgLabel("展示ECharts柱状图组件的各种功能", 'description')
        layout.addWidget(desc_label)
        
        # 基础柱状图示例
        basic_chart_group = TgGroupBox("基础柱状图")
        basic_chart_layout = TgLayout(margins='medium', spacing='medium')
        
        # 操作按钮行
        button_row1 = TgBaseWidget()
        button_layout1 = TgHBoxLayout(margins='none', spacing='medium')
        
        sales_btn = TgButton("销售数据图", 'primary', 'medium')
        sales_btn.clicked.connect(self._show_sales_bar_chart)
        
        profit_btn = TgButton("利润对比图", 'secondary', 'medium')
        profit_btn.clicked.connect(self._show_profit_bar_chart)
        
        horizontal_btn = TgButton("水平柱状图", 'secondary', 'medium')
        horizontal_btn.clicked.connect(self._show_horizontal_bar_chart)
        
        button_layout1.addWidget(sales_btn)
        button_layout1.addWidget(profit_btn)
        button_layout1.addWidget(horizontal_btn)
        button_layout1.addStretch()
        button_row1.setLayout(button_layout1)
        
        basic_chart_layout.addWidget(button_row1)
        
        # 创建柱状图
        self.bar_chart = TgBarChart()
        self.bar_chart.setMinimumHeight(400)
        basic_chart_layout.addWidget(self.bar_chart)
        
        basic_chart_group.setLayout(basic_chart_layout)
        layout.addWidget(basic_chart_group)
        
        # 多系列柱状图示例
        multi_chart_group = TgGroupBox("多系列柱状图")
        multi_chart_layout = TgLayout(margins='medium', spacing='medium')
        
        # 操作按钮行2
        button_row2 = TgBaseWidget()
        button_layout2 = TgHBoxLayout(margins='none', spacing='medium')
        
        compare_btn = TgButton("季度对比图", 'primary', 'medium')
        compare_btn.clicked.connect(self._show_quarter_comparison_chart)
        
        trend_btn = TgButton("销售趋势图", 'secondary', 'medium')
        trend_btn.clicked.connect(self._show_sales_trend_chart)
        
        region_btn = TgButton("区域分析图", 'secondary', 'medium')
        region_btn.clicked.connect(self._show_region_analysis_chart)
        
        button_layout2.addWidget(compare_btn)
        button_layout2.addWidget(trend_btn)
        button_layout2.addWidget(region_btn)
        button_layout2.addStretch()
        button_row2.setLayout(button_layout2)
        
        multi_chart_layout.addWidget(button_row2)
        
        # 创建多系列柱状图
        self.multi_bar_chart = TgBarChart()
        self.multi_bar_chart.setMinimumHeight(400)
        multi_chart_layout.addWidget(self.multi_bar_chart)
        
        multi_chart_group.setLayout(multi_chart_layout)
        layout.addWidget(multi_chart_group)
        
        # 操作状态显示
        status_group = TgGroupBox("图表状态")
        status_layout = TgLayout(margins='medium', spacing='small')
        
        self.chart_status_display = TgTextEdit("柱状图操作状态将显示在这里...")
        self.chart_status_display.setMaximumHeight(100)
        status_layout.addWidget(self.chart_status_display)
        
        status_group.setLayout(status_layout)
        layout.addWidget(status_group)
        
        # 初始化显示销售数据图
        self._show_sales_bar_chart()
        
        layout.addStretch()
        tab.setLayout(layout)
        
        scroll_area.setWidget(tab)
        return scroll_area
    
    def _show_sales_bar_chart(self):
        """显示销售数据柱状图"""
        import pandas as pd
        x_data = ["1月", "2月", "3月", "4月", "5月", "6月"]
        y_data = [320, 332, 301, 334, 390, 330]
        df = pd.DataFrame({"月份": x_data, "销售额(万元)": y_data})
        self.bar_chart.set_title("2024年上半年销售数据")
        self.bar_chart.set_data(df, x_axis_column="月份", y_axis_columns=["销售额(万元)"])
        self.chart_status_display.setPlainText("已显示2024年上半年销售数据柱状图")
    
    def _show_profit_bar_chart(self):
        """显示利润对比柱状图"""
        import pandas as pd
        x_data = ["产品A", "产品B", "产品C", "产品D", "产品E"]
        y_data = [45, 38, 52, 41, 35]
        df = pd.DataFrame({"产品": x_data, "利润率(%)": y_data})
        self.bar_chart.set_title("各产品利润率对比")
        self.bar_chart.set_data(df, x_axis_column="产品", y_axis_columns=["利润率(%)"])
        self.chart_status_display.setPlainText("已显示各产品利润率对比柱状图")
    
    def _show_horizontal_bar_chart(self):
        """显示水平柱状图"""
        import pandas as pd
        y_data = ["北京", "上海", "广州", "深圳", "杭州", "南京", "苏州"]
        x_data = [850, 790, 680, 720, 620, 580, 540]
        df = pd.DataFrame({"城市": y_data, "销售额(万元)": x_data})
        self.bar_chart.set_title("各城市销售额排行")
        self.bar_chart.set_data(df, x_axis_column="城市", y_axis_columns=["销售额(万元)"])
        self.bar_chart.set_horizontal(True)
        self.chart_status_display.setPlainText("已显示各城市销售额排行水平柱状图")
    
    def _show_quarter_comparison_chart(self):
        """显示季度对比柱状图"""
        import pandas as pd
        x_data = ["Q1", "Q2", "Q3", "Q4"]
        series_data = [
            {"name": "2023年", "data": [820, 932, 901, 934]},
            {"name": "2024年", "data": [900, 1045, 1080, 1120]}
        ]
        df = pd.DataFrame()
        df["季度"] = x_data
        y_cols = []
        for series in series_data:
            y_cols.append(series['name'])
            df[series['name']] = series['data']
        self.multi_bar_chart.set_title("季度销售额对比")
        self.multi_bar_chart.set_data(df, x_axis_column="季度", y_axis_columns=y_cols)
        self.chart_status_display.setPlainText("已显示2023-2024年季度销售额对比图")
    
    def _show_sales_trend_chart(self):
        """显示销售趋势图"""
        import pandas as pd
        x_data = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
        series_data = [
            {"name": "线上销售", "data": [320, 332, 301, 334, 390, 330, 320, 332, 301, 334, 390, 330]},
            {"name": "线下销售", "data": [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330]},
            {"name": "代理商", "data": [220, 182, 191, 234, 290, 130, 310, 232, 201, 154, 190, 230]}
        ]
        df = pd.DataFrame()
        df["月份"] = x_data
        y_cols = []
        for series in series_data:
            y_cols.append(series['name'])
            df[series['name']] = series['data']
        self.multi_bar_chart.set_title("全年销售趋势分析")
        self.multi_bar_chart.set_data(df, x_axis_column="月份", y_axis_columns=y_cols)
        self.chart_status_display.setPlainText("已显示全年销售趋势分析图")
    
    def _show_region_analysis_chart(self):
        """显示区域分析图"""
        import pandas as pd
        x_data = ["华北", "华东", "华南", "华中", "西南", "西北", "东北"]
        series_data = [
            {"name": "销售额", "data": [1200, 1500, 1100, 800, 600, 400, 350]},
            {"name": "利润", "data": [240, 300, 220, 160, 120, 80, 70]},
            {"name": "客户数", "data": [45, 58, 42, 30, 25, 18, 15]}
        ]
        df = pd.DataFrame()
        df["区域"] = x_data
        y_cols = []
        for series in series_data:
            y_cols.append(series['name'])
            df[series['name']] = series['data']
        self.multi_bar_chart.set_title("区域销售分析")
        self.multi_bar_chart.set_data(df, x_axis_column="区域", y_axis_columns=y_cols)
        self.chart_status_display.setPlainText("已显示区域销售分析图")
    
    def _create_surface_3d_demo_tab(self) -> TgScrollArea:
        """创建3D曲面图演示选项卡"""
        scroll_area = TgScrollArea()
        
        tab = TgBaseWidget()
        layout = TgLayout(margins='medium', spacing='medium')
        
        # 标题
        title = TgLabel("3D曲面图演示", 'title', 'primary')
        layout.addWidget(title)
        
        desc_label = TgLabel("展示3D曲面图组件，可以显示三维数据的曲面分布", 'description')
        layout.addWidget(desc_label)
        
        # 3D曲面图示例
        surface_chart_group = TgGroupBox("3D曲面图功能")
        surface_chart_layout = TgLayout(margins='medium', spacing='medium')
        
        # 操作按钮行
        button_row = TgBaseWidget()
        button_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        math_surface_btn = TgButton("数学函数曲面", 'primary', 'medium')
        math_surface_btn.clicked.connect(self._show_math_surface)
        
        temperature_btn = TgButton("温度分布曲面", 'secondary', 'medium')
        temperature_btn.clicked.connect(self._show_temperature_surface)
        
        profit_surface_btn = TgButton("利润分析曲面", 'secondary', 'medium')
        profit_surface_btn.clicked.connect(self._show_profit_surface)
        
        random_data_btn = TgButton("随机数据曲面", 'secondary', 'medium')
        random_data_btn.clicked.connect(self._show_random_surface)
        
        button_layout.addWidget(math_surface_btn)
        button_layout.addWidget(temperature_btn)
        button_layout.addWidget(profit_surface_btn)
        button_layout.addWidget(random_data_btn)
        button_layout.addStretch()
        button_row.setLayout(button_layout)
        
        surface_chart_layout.addWidget(button_row)
        
        # 创建3D曲面图
        self.surface_3d_chart = TgSurface3DChart()
        self.surface_3d_chart.setMinimumHeight(500)
        surface_chart_layout.addWidget(self.surface_3d_chart)
        
        surface_chart_group.setLayout(surface_chart_layout)
        layout.addWidget(surface_chart_group)
        
        # 颜色设置组
        color_group = TgGroupBox("颜色设置")
        color_layout = TgLayout(margins='medium', spacing='medium')
        
        color_button_row = TgBaseWidget()
        color_button_layout = TgHBoxLayout(margins='none', spacing='medium')
        
        viridis_btn = TgButton("Viridis配色", 'secondary', 'medium')
        viridis_btn.clicked.connect(lambda: self._set_color_map('viridis'))
        
        plasma_btn = TgButton("Plasma配色", 'secondary', 'medium')
        plasma_btn.clicked.connect(lambda: self._set_color_map('plasma'))
        
        cool_btn = TgButton("Cool配色", 'secondary', 'medium')
        cool_btn.clicked.connect(lambda: self._set_color_map('cool'))
        
        hot_btn = TgButton("Hot配色", 'secondary', 'medium')
        hot_btn.clicked.connect(lambda: self._set_color_map('hot'))
        
        color_button_layout.addWidget(viridis_btn)
        color_button_layout.addWidget(plasma_btn)
        color_button_layout.addWidget(cool_btn)
        color_button_layout.addWidget(hot_btn)
        color_button_layout.addStretch()
        color_button_row.setLayout(color_button_layout)
        
        color_layout.addWidget(color_button_row)
        color_group.setLayout(color_layout)
        layout.addWidget(color_group)
        
        # 操作状态显示
        status_group = TgGroupBox("操作状态")
        status_layout = TgLayout(margins='medium', spacing='small')
        
        self.surface_status_display = TgTextEdit("3D曲面图操作状态将显示在这里...")
        self.surface_status_display.setMaximumHeight(100)
        status_layout.addWidget(self.surface_status_display)
        
        status_group.setLayout(status_layout)
        layout.addWidget(status_group)
        
        # 初始化显示数学函数曲面
        self._show_math_surface()
        
        layout.addStretch()
        tab.setLayout(layout)
        
        scroll_area.setWidget(tab)
        return scroll_area
    
    def _show_math_surface(self):
        """显示数学函数曲面"""
        import pandas as pd
        import numpy as np
        
        # 生成数学函数 z = sin(x) * cos(y) 的数据
        x = np.linspace(-np.pi, np.pi, 20)
        y = np.linspace(-np.pi, np.pi, 20)
        
        data = []
        for xi in x:
            for yi in y:
                zi = np.sin(xi) * np.cos(yi)
                data.append([xi, yi, zi])
        
        df = pd.DataFrame(data, columns=['X', 'Y', 'Z'])
        self.surface_3d_chart.set_title("数学函数曲面: Z = sin(X) * cos(Y)")
        self.surface_3d_chart.set_data(df, 'X', 'Y', 'Z')
        self.surface_status_display.setPlainText("已显示数学函数曲面: Z = sin(X) * cos(Y)")
    
    def _show_temperature_surface(self):
        """显示温度分布曲面"""
        import pandas as pd
        import numpy as np
        
        # 生成模拟温度分布数据
        x = np.linspace(0, 10, 15)  # 经度
        y = np.linspace(0, 10, 15)  # 纬度
        
        data = []
        for xi in x:
            for yi in y:
                # 模拟温度分布：中心温度高，边缘温度低
                distance_from_center = np.sqrt((xi - 5)**2 + (yi - 5)**2)
                temperature = 30 - distance_from_center * 2 + np.random.normal(0, 1)
                data.append([xi, yi, temperature])
        
        df = pd.DataFrame(data, columns=['经度', '纬度', '温度'])
        self.surface_3d_chart.set_title("区域温度分布曲面")
        self.surface_3d_chart.set_data(df, '经度', '纬度', '温度')
        self.surface_status_display.setPlainText("已显示区域温度分布曲面")
    
    def _show_profit_surface(self):
        """显示利润分析曲面"""
        import pandas as pd
        import numpy as np
        
        # 生成利润分析数据
        price = np.linspace(50, 200, 12)  # 价格
        volume = np.linspace(100, 1000, 12)  # 销量
        
        data = []
        for p in price:
            for v in volume:
                # 利润 = (价格 - 成本) * 销量，考虑价格弹性
                cost = 30
                elasticity = max(0.1, 1 - (p - 50) / 200)  # 价格越高，销量越低
                actual_volume = v * elasticity
                profit = (p - cost) * actual_volume / 1000  # 转换为万元
                data.append([p, v, profit])
        
        df = pd.DataFrame(data, columns=['价格', '预期销量', '利润(万元)'])
        self.surface_3d_chart.set_title("产品价格-销量-利润分析曲面")
        self.surface_3d_chart.set_data(df, '价格', '预期销量', '利润(万元)')
        self.surface_status_display.setPlainText("已显示产品价格-销量-利润分析曲面")
    
    def _show_random_surface(self):
        """显示随机数据曲面"""
        import pandas as pd
        import numpy as np
        
        # 生成随机数据
        np.random.seed(42)  # 设置随机种子以获得一致的结果
        x = np.linspace(0, 5, 12)
        y = np.linspace(0, 5, 12)
        
        data = []
        for xi in x:
            for yi in y:
                # 随机高度，带有一些规律性
                zi = np.random.normal(xi + yi, 1) + 2 * np.sin(xi) + np.cos(yi)
                data.append([xi, yi, zi])
        
        df = pd.DataFrame(data, columns=['X坐标', 'Y坐标', '高度'])
        self.surface_3d_chart.set_title("随机数据曲面演示")
        self.surface_3d_chart.set_data(df, 'X坐标', 'Y坐标', '高度')
        self.surface_status_display.setPlainText("已显示随机数据曲面演示")
    
    def _set_color_map(self, color_map):
        """设置颜色映射"""
        self.surface_3d_chart.set_color_map(color_map)
        self.surface_status_display.setPlainText(f"已设置颜色映射为: {color_map}")
        